package com.liangxy.news.ui.splash;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.liangxy.news.R;
import com.liangxy.news.model.AdBanner;
import com.liangxy.news.ui.auth.LoginActivity;
import com.liangxy.news.ui.main.MainActivity;
import com.liangxy.news.util.SharedPreferencesManager;
import com.liangxy.news.util.DatabaseTestUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Splash screen activity with ad carousel
 */
public class SplashActivity extends AppCompatActivity implements AdBannerAdapter.OnBannerClickListener {
    
    private static final String TAG = "SplashActivity";
    private ViewPager2 viewPager;
    private TextView skipButton;
    private LinearLayout indicatorsContainer;
    private int currentPage = 0;
    private int totalAdCount = 0;
    private final int SPLASH_DISPLAY_LENGTH = 5000; // 5 seconds
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable runnable = this::navigateToNextScreen;
    private CountDownTimer countDownTimer;
    private List<ImageView> indicators;
    
    private SharedPreferencesManager preferencesManager;
    private int countdownSeconds = 5;
    private List<AdBanner> adBanners;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        
        preferencesManager = new SharedPreferencesManager(this);
        
        // 初始化视图
        viewPager = findViewById(R.id.viewPager);
        skipButton = findViewById(R.id.skipButton);
        indicatorsContainer = findViewById(R.id.indicatorsContainer);
        
        // 初始化数据库并检查表结构
        DatabaseTestUtil.initializeDatabase(this);
        
        // 初始化广告数据
        adBanners = getAdBanners();
        totalAdCount = adBanners.size();
        
        // 设置ViewPager轮播
        setupAdCarousel();
        
        // 设置指示器
        setupIndicators(totalAdCount);
        
        // 设置倒计时
        setupCountdownTimer();
        
        // Skip button click listener
        skipButton.setOnClickListener(v -> navigateToNextScreen());
    }
    
    /**
     * 初始化广告数据
     */
    private List<AdBanner> getAdBanners() {
        List<AdBanner> banners = new ArrayList<>();
        
        // 添加本地布局广告
        banners.add(AdBanner.createWithLayout(R.layout.ad_banner_news, "新闻时刻头条", "news://category/top"));
        banners.add(AdBanner.createWithLayout(R.layout.ad_banner_tech, "科技前沿资讯", "news://category/keji"));
        banners.add(AdBanner.createWithLayout(R.layout.ad_banner_finance, "财经市场动态", "news://category/caijing"));
        banners.add(AdBanner.createWithLayout(R.layout.ad_banner_entertainment, "娱乐星闻焦点", "news://category/yule"));
        banners.add(AdBanner.createWithLayout(R.layout.ad_banner_sports, "体育赛事追踪", "news://category/tiyu"));
        
        return banners;
    }
    
    /**
     * Setup ad carousel
     */
    private void setupAdCarousel() {
        // Setup adapter
        AdBannerAdapter adapter = new AdBannerAdapter(adBanners);
        adapter.setOnBannerClickListener(this);
        viewPager.setAdapter(adapter);
        
        // Page change listener
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                updateIndicators(position);
                Log.d(TAG, "广告页面切换：" + position);
            }
        });
        
        // 自动滚动
        if (totalAdCount > 1) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (viewPager == null || isFinishing()) return;
                    
                    int nextPage = (currentPage + 1) % totalAdCount;
                    viewPager.setCurrentItem(nextPage, true);
                    handler.postDelayed(this, 3000); // 每3秒切换一次
                }
            }, 3000);
        }
    }
    
    /**
     * 设置指示器
     */
    private void setupIndicators(int count) {
        indicators = new ArrayList<>();
        indicatorsContainer.removeAllViews();
        
        if (count <= 1) {
            indicatorsContainer.setVisibility(View.GONE);
            return;
        }
        
        indicatorsContainer.setVisibility(View.VISIBLE);
        for (int i = 0; i < count; i++) {
            ImageView indicator = new ImageView(this);
            int size = (int) (getResources().getDisplayMetrics().density * 8);
            int margin = (int) (getResources().getDisplayMetrics().density * 4);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
            params.setMargins(margin, 0, margin, 0);
            indicator.setLayoutParams(params);
            indicator.setImageResource(i == 0 ? R.drawable.indicator_selected : R.drawable.indicator_unselected);
            indicators.add(indicator);
            indicatorsContainer.addView(indicator);
        }
    }
    
    /**
     * 更新指示器状态
     */
    private void updateIndicators(int position) {
        if (indicators == null || indicators.isEmpty()) return;
        
        for (int i = 0; i < indicators.size(); i++) {
            indicators.get(i).setImageResource(
                i == position ? R.drawable.indicator_selected : R.drawable.indicator_unselected
            );
        }
    }
    
    /**
     * 设置倒计时
     */
    private void setupCountdownTimer() {
        skipButton.setText("跳过 (" + countdownSeconds + ")");
        countDownTimer = new CountDownTimer(countdownSeconds * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                skipButton.setText("跳过 (" + seconds + ")");
            }
            
            @Override
            public void onFinish() {
                navigateToNextScreen();
            }
        };
        countDownTimer.start();
    }
    
    /**
     * Navigate to next screen based on login status
     */
    private void navigateToNextScreen() {
        // Cancel timers
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        handler.removeCallbacksAndMessages(null);
        
        // Navigate to login or main activity based on login status
        Intent intent;
        if (preferencesManager.isLoggedIn()) {
            intent = new Intent(SplashActivity.this, MainActivity.class);
        } else {
            intent = new Intent(SplashActivity.this, LoginActivity.class);
        }
        startActivity(intent);
        finish();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        handler.removeCallbacksAndMessages(null);
    }
    
    @Override
    public void onBannerClick(AdBanner banner, int position) {
        // 处理广告点击
        Toast.makeText(this, "点击了: " + banner.getTitle(), Toast.LENGTH_SHORT).show();
        
        // 根据广告链接跳转到相应的页面
        if (banner.getLink() != null && banner.getLink().startsWith("news://")) {
            // 这里可以根据scheme处理内部导航
            String path = banner.getLink().substring("news://".length());
            handleInternalNavigation(path);
        } else if (banner.getLink() != null) {
            // 外部链接处理
            // 可以启动浏览器或应用内WebView
        }
    }
    
    /**
     * 处理应用内导航
     */
    private void handleInternalNavigation(String path) {
        // 可以根据path处理不同的内部导航
        Intent intent;
        if (path.startsWith("category/")) {
            String category = path.substring("category/".length());
            intent = new Intent(this, MainActivity.class);
            intent.putExtra("OPEN_CATEGORY", category);
            countDownTimer.cancel();
            startActivity(intent);
            finish();
        }
    }
} 